package com.alvis.media.controller.admin;

import com.alvis.media.base.BaseApiController;
import com.alvis.media.base.NonStaticResourceHttpRequestHandler;
import com.alvis.media.base.RestResponse;
import com.alvis.media.constant.VideoInfoConstant;
import com.alvis.media.domain.User;
import com.alvis.media.domain.VideoInfo;
import com.alvis.media.service.VideoInfoService;
import com.alvis.media.utility.DateTimeUtil;
import com.alvis.media.utility.PageInfoHelper;
import com.alvis.media.viewmodel.video.*;
import com.example.fileupload.entity.FileInfo;
import com.example.fileupload.service.FileService;
import com.github.pagehelper.PageInfo;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartException;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController("VideoController")
@RequestMapping(value = "/api/admin/video")
@AllArgsConstructor
public class VideoController extends BaseApiController {
    private static final Logger logger = LoggerFactory.getLogger(VideoController.class);
    
    // DI/IoC
    @Autowired
    private VideoInfoService videoInfoService;

    @Autowired
    private NonStaticResourceHttpRequestHandler nonStaticResourceHttpRequestHandler;
    
    @Autowired
    private FileService fileService;

    /**
     * 视频播放
     */
    @GetMapping("/play/**/*")
    public void playVideo(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //realPath 即视频所在的完整地址
        String url = request.getRequestURL().toString();
        int index = url.lastIndexOf("D:");
        String realPath = url.substring(index);

        Path filePath = Paths.get(realPath);
        if (Files.exists(filePath)) {
            // 利用 Files.probeContentType 获取文件类型
            String mimeType = Files.probeContentType(filePath);
            if (!StringUtils.isEmpty(mimeType)) {
                // 设置 response
                response.setContentType(mimeType);
            }
            request.setAttribute(nonStaticResourceHttpRequestHandler.filepath, filePath);
            // 利用 ResourceHttpRequestHandler.handlerRequest() 实现返回视频流
            nonStaticResourceHttpRequestHandler.handleRequest(request, response);
        } else {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            response.setCharacterEncoding(StandardCharsets.UTF_8.toString());
        }
    }

    /**
     * 视频列表
     */
    @RequestMapping(value = "/page/list", method = RequestMethod.POST)
    public RestResponse<PageInfo<VideoResponseVM>> pageList(@RequestBody VideoPageRequestVM model) {
        PageInfo<VideoInfo> videoPageInfo = videoInfoService.videoPage(model);

        // 将PageInfo<User> userPageInfo类型 --> PageInfo<UserResponseVM>类型
        PageInfo<VideoResponseVM> videoResponseVM = PageInfoHelper.copyMap(videoPageInfo, (d) -> VideoResponseVM.from(d));
        return RestResponse.ok(videoResponseVM);
    }

    /**
     * 添加视频
     */
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    public RestResponse<VideoResponseVM> createVideo(@RequestBody @Valid VideoCreateVM model) {
        VideoInfo videoInfo = modelMapper.map(model, VideoInfo.class);

        String videoURL = model.getVideoUrl();
        // 校验用户是否上传视频，如果未上传，则给用户提示“视频文件未上传”
        if (StringUtils.isBlank(videoURL)) {
            return RestResponse.fail(VideoInfoConstant.VIDEO_FILE_NOT_UPLOADED, "视频文件未上传");
        }

        if (model.getVideoCategory() == null) {
            return RestResponse.fail(VideoInfoConstant.VIDEO_CATEGORY_IS_NULL, "视频分类不能为空");
        }

        if (model.getVideoName() == null) {
            return RestResponse.fail(VideoInfoConstant.VIDEO_NAME_IS_NULL, "视频名称为NULL了");
        }

        User currentUser = getCurrentUser(); // 获取当前登录的用户

        videoInfo.setCreatorId(currentUser.getId()); // 视频的创建者的编号
        videoInfo.setVideoCategory(model.getVideoCategory()); // 设置视频分类
        videoInfo.setVideoName(model.getVideoName()); // 设置视频名称
        videoInfo.setCreateTime(new Date());
        String newVideoUrl = DateTimeUtil.getCurrentTimeYMD() + StringUtils.substring(videoURL, StringUtils.lastIndexOf(videoURL, "/"));
        videoInfo.setVideoUrl(newVideoUrl);
        videoInfoService.insertByFilter(videoInfo); // 调用service层做入库操作
        return RestResponse.ok();
    }

    @RequestMapping(value = "/select/{id}", method = RequestMethod.POST)
    public RestResponse<VideoResponseVM> select(@PathVariable Integer id) {
        // 确保返回的数据包含 videoName 字段
        VideoInfo videoInfo = videoInfoService.selectById(id);
        if (videoInfo == null) {
            return RestResponse.fail(VideoInfoConstant.VIDEO_NOT_FOUND, "视频信息不存在");
        }

        VideoResponseVM vm = VideoResponseVM.from(videoInfo);
        return RestResponse.ok(vm);
    }



    @RequestMapping(value = "/getVideoDetailByVideoId/{id}", method = RequestMethod.POST)
    public RestResponse<VideoDetailVM> getVideoDetailByVideoId(@PathVariable Integer id) {
        if (id == null) {
            return RestResponse.fail(VideoInfoConstant.VIDEO_ID_IS_NULL, "视频ID不能为空");
        }
        
        // 查询视频信息
        VideoInfo videoInfo = videoInfoService.selectById(id);
        if (videoInfo == null) {
            return RestResponse.fail(VideoInfoConstant.VIDEO_NOT_FOUND, "视频信息不存在");
        }
        
        // 构建返回的视图模型
        VideoDetailVM vm = new VideoDetailVM();
        vm.setVideoId(videoInfo.getVideoId());
        vm.setVideoName(videoInfo.getVideoName());
        
        // 设置视频分类
        vm.setVideoCategory(videoInfo.getVideoCategory());
        
        // 这里可以根据实际情况添加标签列表、播放记录等信息
        // 目前返回空的标签列表，后续可以从数据库查询
        vm.setVideoTagList(new ArrayList<>());
        
        return RestResponse.ok(vm);
    }

    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    public RestResponse<VideoResponseVM> editVideo(
            @RequestBody VideoEditVM model) {
        // 从请求体中获取视频ID
        Integer id = model.getVideoId();
        // 校验必填字段
        if (id == null) {
            return RestResponse.fail(VideoInfoConstant.VIDEO_ID_IS_NULL, "视频ID不能为空");
        }

        if (StringUtils.isBlank(model.getVideoName())) {
            return RestResponse.fail(VideoInfoConstant.VIDEO_NAME_IS_NULL, "视频名称不能为空");
        }

        if (model.getVideoCategory() == null) {
            return RestResponse.fail(VideoInfoConstant.VIDEO_CATEGORY_IS_NULL, "视频分类不能为空");
        }

        // 查询原视频信息
        VideoInfo videoInfo = videoInfoService.selectById(id);
        if (videoInfo == null) {
            return RestResponse.fail(VideoInfoConstant.VIDEO_NOT_FOUND, "视频信息不存在");
        }

        // 更新字段
        videoInfo.setVideoName(model.getVideoName());
        videoInfo.setVideoCategory(model.getVideoCategory());
        videoInfo.setLastModifyTime(new Date()); // 更新最后修改时间

        // 执行更新 - 使用updateByIdFilter只更新非null字段
        videoInfoService.updateByIdFilter(videoInfo);

        // 如果前端传入了标签列表，可以在这里处理标签的更新
        // 由于数据库中没有video_tag表，暂时不处理标签的持久化
        // 后续可以创建VideoTagService和相关Mapper来处理标签管理

        // 重新查询以获取完整的更新后数据
        VideoInfo updatedVideoInfo = videoInfoService.selectById(id);
        // 返回更新后的数据
        VideoResponseVM vm = VideoResponseVM.from(updatedVideoInfo);
        return RestResponse.ok(vm);
    }



    @RequestMapping(value = "/delete/{id}", method = RequestMethod.POST)
    public RestResponse delete(@PathVariable Integer id) {
        // 检查ID是否有效
        if (id == null) {
            return RestResponse.fail(VideoInfoConstant.VIDEO_ID_IS_NULL, "视频ID不能为空");
        }

        // 查找要删除的视频信息
        VideoInfo videoInfo = videoInfoService.selectById(id);
        if (videoInfo == null) {
            return RestResponse.fail(VideoInfoConstant.VIDEO_NOT_FOUND, "未找到对应视频信息");
        }

        // 删除视频记录
        videoInfoService.deleteById(id);

        return RestResponse.ok("视频删除成功");
    }

    @RequestMapping(value = "/userAnalysis/{id}", method = RequestMethod.POST)
    public RestResponse<UserAnalysisVM> userAnalysis(@PathVariable Integer id) {
        UserAnalysisVM vm = new UserAnalysisVM();
        return RestResponse.ok(vm);
    }
    
    /**
     * 视频文件上传接口
     * 接收MultipartFile格式的视频文件，保存后返回文件信息
     */
    @PostMapping("/upload")
    public ResponseEntity<Map<String, Object>> uploadVideoFile(@RequestParam("file") MultipartFile file) {
        logger.info("接收到视频文件上传请求");
        Map<String, Object> response = new HashMap<>();
        
        try {
            if (file == null) {
                logger.error("上传的视频文件为null");
                response.put("code", 400);
                response.put("message", "视频文件不能为空");
                return ResponseEntity.badRequest().body(response);
            }
            
            if (file.isEmpty()) {
                logger.error("上传的视频文件内容为空");
                response.put("code", 400);
                response.put("message", "视频文件内容不能为空");
                return ResponseEntity.badRequest().body(response);
            }
            
            logger.info("视频文件名: {}", file.getOriginalFilename());
            
            // 调用FileService保存文件
            FileInfo savedFile = fileService.saveFile(file);
            
            logger.info("视频文件上传成功，文件ID: {}", savedFile.getId());
            response.put("code", 200);
            response.put("message", "视频文件上传成功");
            response.put("response", savedFile);
            
            return ResponseEntity.ok(response);
        } catch (MultipartException e) {
            logger.error("视频文件上传格式错误: {}", e.getMessage());
            response.put("code", 400);
            response.put("message", "请求必须是multipart/form-data格式，请正确设置Content-Type");
            return ResponseEntity.badRequest().body(response);
        } catch (IOException e) {
            logger.error("视频文件上传失败", e);
            response.put("code", 500);
            response.put("message", "系统内部错误: " + e.getMessage());
            return ResponseEntity.status(500).body(response);
        } catch (Exception e) {
            logger.error("视频文件上传过程中发生未知错误", e);
            response.put("code", 500);
            response.put("message", "系统内部错误: " + e.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }
}
